Azure Content Understanding in Spark
Azure Content Understanding (CU) turns unstructured content into structured information. In this quickstart, use SynapseML to extract a purchase order's supplier, total, and delivery date, generate a summary, and inspect confidence and source information.
Follow the steps in order. The example creates a fictional document and uses SynapseML, PySpark, and the Python standard library.
1. Setting Up
Before you begin, set up:
- A Spark environment with matching SynapseML Python and JVM packages that include
ContentUnderstanding. See the installation instructions. - A CU resource configured for
prebuilt-documentand the models below, with permission to create analyzers. See the CU REST quickstart. - Durable storage that your Spark driver and executors can read and write.
Use a development resource: requests are billable, and step 3 creates an analyzer. The notebook doesn't provision resources or change model defaults.
Provide these driver environment variables, or enter them when prompted. Retrieve the key from your secret manager; don't save it in notebook cells or outputs.
| Setting | What to provide |
|---|---|
CONTENT_UNDERSTANDING_ENDPOINT | Resource root: https://<resource>.services.ai.azure.com. |
CONTENT_UNDERSTANDING_API_KEY | Resource key; the prompt hides your input. |
CONTENT_UNDERSTANDING_OUTPUT_PATH | Shared storage, such as Files/cu-semantic-example in an attached Fabric Lakehouse, not a driver-local directory. |
Keep the printed run identifier and storage path for recovery. Leave optional environment variables unset for your first run; deployment overrides are covered in request options.
import getpass
import json
import os
import re
import uuid
from urllib.parse import urlsplit
from pyspark.sql import SparkSession, functions as F
from synapse.ml.services.contentunderstanding import ContentUnderstanding
spark = SparkSession.builder.getOrCreate()
endpoint = (
os.environ.get("CONTENT_UNDERSTANDING_ENDPOINT")
or input("CU resource endpoint: ").strip()
)
key = os.environ.get("CONTENT_UNDERSTANDING_API_KEY") or getpass.getpass(
"CU resource key (not displayed): "
)
storage_root = (
os.environ.get("CONTENT_UNDERSTANDING_OUTPUT_PATH")
or input("Durable Spark output directory: ").strip()
)
run_id = (
os.environ.get("CONTENT_UNDERSTANDING_RUN_ID", "").strip() or uuid.uuid4().hex[:12]
)
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,38}", run_id):
raise ValueError(
"Run ID must be 1-39 letters, digits, hyphens or underscores, "
"starting with a letter or digit."
)
if not endpoint or not key or not storage_root:
raise ValueError("An endpoint, resource key, and output directory are required.")
def resource_origin(url: str) -> str:
try:
parsed = urlsplit(url)
if (
parsed.scheme not in ("http", "https")
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
):
return ""
port = parsed.port
if port is None:
port = 443 if parsed.scheme == "https" else 80
return f"{parsed.scheme}://{parsed.hostname}:{port}"
except ValueError:
return ""
endpoint_origin = resource_origin(endpoint)
if not endpoint_origin:
raise ValueError("Configure a valid CU resource endpoint without user information.")
run_root = storage_root.rstrip("/") + "/" + run_id
handles_path = run_root + "/submitted"
analyzer_id = "synapseml_purchase_order_" + run_id.replace("-", "_")
print("Run identifier:", run_id)
print("Saved submission path:", handles_path)
print("Custom analyzer identifier:", analyzer_id)
2. Create a sample document
The next cell creates a one-page purchase order for 10 notebooks from Contoso Office Supplies and puts it in a Spark DataFrame. The document includes a total and delivery date, so you can check the results easily. No download or PDF library is needed.
page_text = b"""BT /F1 14 Tf 50 740 Td
(SYNTHETIC PURCHASE ORDER PO-1001) Tj
0 -30 Td (Supplier: Contoso Office Supplies) Tj
0 -30 Td (Buyer: Research) Tj
0 -30 Td (Order date: 2026-01-15) Tj
0 -30 Td (Items: 10 notebooks at USD 12.50 each.) Tj
0 -30 Td (Total amount: USD 125.00) Tj
0 -30 Td (Delivery requested by 2026-02-01.) Tj
ET"""
pdf_objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Resources << /Font << /F1 3 0 R >> >> /Contents 5 0 R >>",
f"<< /Length {len(page_text)} >>\nstream\n".encode("ascii")
+ page_text
+ b"\nendstream",
]
pdf_bytes = bytearray(b"%PDF-1.4\n")
offsets = [0]
for number, pdf_object in enumerate(pdf_objects, 1):
offsets.append(len(pdf_bytes))
pdf_bytes.extend(f"{number} 0 obj\n".encode("ascii") + pdf_object + b"\nendobj\n")
xref_offset = len(pdf_bytes)
pdf_bytes.extend(f"xref\n0 {len(offsets)}\n0000000000 65535 f \n".encode("ascii"))
for offset in offsets[1:]:
pdf_bytes.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
pdf_bytes.extend(
(
f"trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\n"
f"startxref\n{xref_offset}\n%%EOF\n"
).encode("ascii")
)
documents = spark.createDataFrame(
[("PO-1001", "purchase-order.pdf", pdf_bytes)],
"documentId string, documentName string, content binary",
).coalesce(1)
3. Tell CU what to extract
An analyzer tells CU what to look for. Here, fieldSchema defines Supplier, TotalAmount, RequestedDeliveryDate, and OrderSummary, with descriptions that guide extraction or generation. The analyzer uses gpt-6.1-sol for completion and requests confidence and source information.
Run this cell once for a new run. It won't replace an existing analyzer by default. If creation fails or times out, check getAnalyzer() before retrying. See analyzer management for details. To resume an existing analysis, follow step 5 instead.
try:
model_deployments = json.loads(
os.environ.get("CONTENT_UNDERSTANDING_MODEL_DEPLOYMENTS", "").strip() or "{}"
)
except json.JSONDecodeError as error:
raise ValueError(
"Model deployments must be a JSON object of nonempty strings."
) from error
if not isinstance(model_deployments, dict) or any(
not isinstance(name, str)
or not name.strip()
or not isinstance(deployment, str)
or not deployment.strip()
for name, deployment in model_deployments.items()
):
raise ValueError("Model deployments must be a JSON object of nonempty strings.")
definition = {
"baseAnalyzerId": "prebuilt-document",
"description": "Extract a synthetic purchase order and summarize its purpose.",
"models": {
"completion": "gpt-6.1-sol",
"embedding": "text-embedding-3-large",
},
"config": {
"returnDetails": True,
"estimateFieldSourceAndConfidence": True,
},
"fieldSchema": {
"name": "PurchaseOrder",
"fields": {
"Supplier": {
"type": "string",
"description": "The company supplying the ordered goods, not the buyer.",
"method": "extract",
},
"TotalAmount": {
"type": "number",
"description": "The total purchase-order amount, excluding the currency label.",
"method": "extract",
},
"RequestedDeliveryDate": {
"type": "date",
"description": "The requested delivery date, not the order creation date.",
"method": "extract",
},
"OrderSummary": {
"type": "string",
"description": "Summarize in one sentence who is buying what, from whom, and by when.",
"method": "generate",
},
},
},
}
analyzer = (
ContentUnderstanding()
.setEndpoint(endpoint)
.setSubscriptionKey(key)
.setAnalyzerId(analyzer_id)
.setDocumentBytesCol("content")
.setDocumentNameCol("documentName")
.setMimeType("application/pdf")
.setStringEncoding("codePoint")
.setOutputCol("analysis")
.setErrorCol("requestError")
)
if model_deployments:
analyzer.setModelDeployments(model_deployments)
created = json.loads(analyzer.createAnalyzer(definition))
if created.get("status", "").lower() != "ready":
raise RuntimeError(
"The analyzer is not ready; inspect it before submitting documents."
)
print("Analyzer ready:", created["analyzerId"])
4. Send the document and save its tracking information
CU returns an operation handle to track each analysis. The next cell saves it, the document ID, response, and diagnostics to Parquet so you can retrieve results later.
The write sends the request. Inspect only the reloaded submitted DataFrame: another action on the original transformed DataFrame would submit again.
The default write mode prevents overwriting saved files, not duplicate requests. Task retries can duplicate submissions; investigate uncertain failures before resubmitting.
submitter = analyzer.copy().setOperationMode("submit")
submitter.transform(documents).select(
"documentId", "analysis", "requestError"
).write.parquet(handles_path)
submitted = spark.read.parquet(handles_path)
submitted.select("documentId", "analysis.status", "analysis.httpStatus").show(
truncate=False
)
5. Check progress and retrieve the results
Polling checks saved handles for results. On your first pass, leave the paths unchanged to save a poll-001 snapshot.
For NotStarted, Running, or Unknown rows with a handle, use the latest snapshot as input and a new output path, such as poll-002. Repeat steps 5-6, not submission.
After a session restart, run step 1 with the original CONTENT_UNDERSTANDING_RUN_ID, storage root, and CU endpoint, then jump here. You don't need to recreate the analyzer or document.
Investigate Unknown rows without handles and ResultUnavailable before resubmitting. For status handling, cancellation, and throttling, see submit and poll guidance and polling limits.
recovery_input_path = handles_path
recovery_output_path = run_root + "/poll-001"
saved = spark.read.parquet(recovery_input_path)
resumable = F.col("analysis.operationLocation").isNotNull() & F.col(
"analysis.status"
).isin("NotStarted", "Running", "Unknown")
pending = saved.where(resumable).select(
"documentId", F.col("analysis.operationLocation").alias("operationHandle")
)
handle_origin = F.udf(resource_origin, "string")
if (
pending.where(~handle_origin("operationHandle").eqNullSafe(F.lit(endpoint_origin)))
.limit(1)
.count()
):
raise ValueError(
"Saved handles do not match the configured CU endpoint. "
"Restore the original endpoint; no new snapshot was written."
)
settled = saved.where(~resumable).select("documentId", "analysis", "requestError")
poller = (
ContentUnderstanding()
.setEndpoint(endpoint)
.setSubscriptionKey(key)
.setOperationMode("poll")
.setOperationLocationCol("operationHandle")
.setOutputCol("analysis")
.setErrorCol("requestError")
)
polled = poller.transform(pending).select("documentId", "analysis", "requestError")
settled.unionByName(polled).write.parquet(recovery_output_path)
results = spark.read.parquet(recovery_output_path)
results.selectExpr(
"documentId",
"analysis.status AS status",
"analysis.httpStatus AS httpStatus",
"get_json_object(analysis.error, '$.code') AS diagnosticCode",
).show(truncate=False)
6. Explore the extracted information
The next cell displays fields from saved results with status Succeeded. Compare them with these expected values, not a recorded service response:
| Field | Expected result |
|---|---|
Supplier | Contoso Office Supplies |
TotalAmount | 125.0 |
RequestedDeliveryDate | 2026-02-01 |
OrderSummary | Research buying 10 notebooks from Contoso Office Supplies, with delivery requested by 2026-02-01. Wording can vary. |
confidence is a service estimate, not an accuracy guarantee. source encodes locations in the document; spans identify passages shown as supportingText. Missing values remain null, including confidence or grounding for generated summaries.
An empty table doesn't establish success: check step 5's diagnostics. This example handles string, number, and date fields across all content entries; extend response_schema for other types. The saved rawResponse preserves the complete result.
# Separate closing brackets so IPython does not interpret them as a prompt.
response_schema = """
STRUCT<result: STRUCT<contents: ARRAY<STRUCT<
markdown: STRING,
fields: MAP<STRING, STRUCT<
type: STRING,
valueString: STRING,
valueNumber: DOUBLE,
valueDate: STRING,
confidence: DOUBLE,
source: STRING,
spans: ARRAY<STRUCT<offset: INT, length: INT>>
>>
> > > >
"""
completed = results.where("analysis.status = 'Succeeded'")
contents = completed.select(
"documentId",
F.posexplode(
F.from_json("analysis.rawResponse", response_schema)
.getField("result")
.getField("contents")
).alias("contentIndex", "content"),
)
fields = contents.select(
"documentId",
"contentIndex",
"content.markdown",
F.explode("content.fields").alias("fieldName", "field"),
)
extracted = fields.select(
"documentId",
"contentIndex",
"fieldName",
F.col("field.type").alias("type"),
F.coalesce(
F.col("field.valueString"),
F.col("field.valueNumber").cast("string"),
F.col("field.valueDate"),
).alias("value"),
F.col("field.confidence").alias("confidence"),
F.col("field.source").alias("source"),
F.col("field.spans").alias("spans"),
F.expr(
"transform(field.spans, span -> substring(markdown, span.offset + 1, span.length))"
).alias("supportingText"),
)
extracted.orderBy("documentId", "contentIndex", "fieldName").show(truncate=False)
contents.select("documentId", "contentIndex", "content.markdown").show(truncate=False)
When you're finished
Keep your latest snapshot and complete results in protected storage; service handles can expire. The analyzer remains in your resource until you remove it with your resource-management tools.
Learn more: